<?php

/**
 * 订阅消息
 * @Author: Helloweba
 * @Date:   2020-01-01 20:24:57
 * @Last Modified by:   Helloweba
 * @Last Modified time: 2020-01-05 20:17:16
 */

require_once __DIR__ . '/../vendor/autoload.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;

$exchange = 'article';
$routerKey = 'history'; //只消费玄幻类消息

//$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$connection = new AMQPStreamConnection(
    'localhost',
    5673,
    'admin',  //user
    'admin'   //password
);

$channel = $connection->channel();

$channel->exchange_declare($exchange, 'direct', false, false, false);

list($queueName, ,) = $channel->queue_declare("", false, false, false, false);

$channel->queue_bind($queueName, $exchange, $routerKey);

echo " [*] Waiting for messages. To exit press CTRL+C" .PHP_EOL;
$callback = function ($msg) {
    //echo " Received message：", $msg->body, PHP_EOL;
    echo ' Received message：',$msg->delivery_info['routing_key'], ':', $msg->body, PHP_EOL;
    sleep(1);  //模拟耗时执行
};
$channel->basic_consume($queueName, '', false, true, false, false, $callback);

while ($channel->is_consuming()) {
    $channel->wait();
}

$channel->close();
$connection->close();
